package me.stone.stanimeclient.core.ui.adapters

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import me.stone.stanimeclient.core.common.extensions.dip
import me.stone.stanimeclient.core.model.FanRankItem
import me.stone.stanimeclient.core.ui.adapters.base.AbsViewDataBoundAdapter
import me.stone.stanimeclient.core.ui.databinding.ItemRankLineBinding
import java.util.concurrent.Executor
import kotlin.math.roundToInt

class FanRankAdapter(
    backExecutor: Executor
) : AbsViewDataBoundAdapter<FanRankItem, ItemRankLineBinding>(
    backExecutor = backExecutor,
    diffCallback = DIFF_CALLBACK
) {

    companion object {
        private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<FanRankItem>() {
            override fun areItemsTheSame(oldItem: FanRankItem, newItem: FanRankItem): Boolean {
                return oldItem.id == newItem.id
            }

            override fun areContentsTheSame(oldItem: FanRankItem, newItem: FanRankItem): Boolean {
                return oldItem == newItem
            }
        }
    }

    override fun createDataBinding(parent: ViewGroup): ItemRankLineBinding {
        return ItemRankLineBinding.inflate(
            LayoutInflater.from(parent.context), parent, false
        )
    }

    override fun bindData(binding: ItemRankLineBinding, item: FanRankItem, position: Int) {
        binding.item = item
    }

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(recyclerView.context)
        if (recyclerView.paddingStart == 0 || recyclerView.paddingLeft == 0) {
            val dp8 = 8f.dip.roundToInt()
            recyclerView.setPaddingRelative(dp8, 0, dp8, 0)
        }
        if (recyclerView.itemDecorationCount == 0) {
            recyclerView.addItemDecoration(
                DividerItemDecoration(recyclerView.context, DividerItemDecoration.VERTICAL)
            )
        }
    }

}